<!--
 * @Author: Dorange.Wang
 * @Date: 2021-03-31 15:57:59
 * @LastEditors: your name
 * @LastEditTime: 2021-09-24 10:26:04
 * @Description: file content
-->
<route>
{
"meta":{
"title":"业务模型",
"showMenu":true,
"serialNum": 10
}
}
</route>

<template>
  <div>
    <el-row :gutter="12">
      <el-col :span="6">
        <el-select
          v-model="queryData.modelTypes"
          placeholder="模型类型"
          style="width: 100%"
          clearable
          multiple
        >
          <el-option
            v-for="(value, key) in MODULE_TYPE_ENUM"
            :key="key"
            :value="key"
            :label="value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6">
        <el-input
          v-model="queryData.searchKey"
          placeholder="模型编码或模型名称"
          size="small"
          clearable
          :maxlength="64"
          prefix-icon="el-icon-search"
        />
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="loadData(1, 'search')"
          >查询
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-col>
      <el-col :span="24" class="mt10">
        <DropdownButtons
          :buttons="[
            {
              icon: 'el-icon-circle-plus-outline',
              command: 'model',
              title: '新建模型',
            },
            {
              icon: 'el-icon-upload2',
              command: 'importModel',
              title: '导入模型',
              upload: {
                accept: '.hm_model',
                httpRequest: handleHttpRequest,
              },
            },
            ...(isDefault
              ? [
                  {
                    icon: 'el-icon-folder-add',
                    command: 'folder',
                    title: '新建文件夹',
                  },
                ]
              : []),
          ]"
          @command="handleCreate"
        />
      </el-col>
    </el-row>
    <template
      v-if="folderData && folderData.length > 0 && isDefault && !searchResFlag"
    >
      <div class="mt10" style="height: 1px"></div>
      <el-divider content-position="left">模型管理</el-divider>
      <el-row :gutter="12">
        <el-col :span="6" v-for="folder in folderData" :key="folder.id">
          <el-card class="folder-card mb10" shadow="hover">
            <div class="folder-content" @click="handleFolderClick(folder)">
              <i class="el-icon-folder"></i>
              <span :title="folder.name" class="folder-title">{{
                folder.name
              }}</span>
            </div>
            <el-dropdown
              class="menu"
              placement="bottom"
              trigger="click"
              size="medium"
              @command="handleFolderCommand($event, folder)"
            >
              <i class="el-icon-more"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-card>
        </el-col>
      </el-row>
    </template>

    <div class="mt10" style="height: 1px"></div>
    <el-divider v-if="searchResFlag" content-position="left">
      <span class="root-link" @click="loadAllData">模型管理</span>
      <i class="el-icon-arrow-right"></i>
      查询结果（{{ total }}）
    </el-divider>
    <el-divider v-else-if="isDefault" content-position="left"
      >默认（{{ total }}）
    </el-divider>
    <el-divider v-else content-position="left">
      <span class="root-link" @click="loadAllData">模型管理</span>
      <i class="el-icon-arrow-right"></i>
      {{ currentFolder.name }}
    </el-divider>
    <el-table
      class="mt10"
      :data="tableData"
      v-loading="loading"
      style="width: 100%"
      current-row-key="id"
      stripe
      border
    >
      <el-table-column prop="code" label="模型编码">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleInfo(scope.row)"
            class="limit"
            :title="scope.row.code"
            >{{ scope.row.code }}
          </el-button>
          <el-button
            style="opacity: 0.8"
            type="text"
            @click="copy(scope.row.code)"
            icon="el-icon-document-copy"
          ></el-button>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="模型名称" />
      <el-table-column prop="type" label="模型类型" width="150">
        <template slot-scope="scope">
          {{ scope.row.type | moduleType }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="模型描述" />
      <el-table-column prop="version" label="当前版本号" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.version">
            {{ scope.row.version | version }}
            <i
              class="el-icon-edit ml10 version-edit"
              title="切换版本"
              @click="handleVersionActivate(scope.row)"
            ></i>
          </span>
          <el-button
            v-else
            type="text"
            @click="handleVersionActivate(scope.row)"
            >激活版本
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="modifyDate" label="更新时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.modifyDate | moment }}
        </template>
      </el-table-column>
      <el-table-column prop="actions" label="操作" width="250">
        <template slot-scope="scope">
          <span class="table-actionItem"
            ><el-button type="text" @click="handleMove(scope.row)"
              >移动</el-button
            ></span
          >
          <span class="table-actionItem"
            ><el-button type="text" @click="handleEdit(scope.row)"
              >编辑</el-button
            ></span
          >
          <span class="table-actionItem">
            <el-popconfirm
              title="确定要删除该模型吗？"
              placement="top"
              @confirm="handleDelete(scope.row)"
            >
              <el-button class="link-danger" type="text" slot="reference"
                >删除</el-button
              >
            </el-popconfirm>
          </span>
          <span class="table-actionItem">
            <el-popconfirm
              :title="`${
                scope.row.permissionCtrl
                  ? '确定要取消权限管控吗?'
                  : '确定加入权限控制吗?'
              }`"
              placement="top"
              @confirm="setAuth(scope.row)"
            >
              <el-button type="text" slot="reference">{{
                scope.row.permissionCtrl ? "取消权限" : "添加权限"
              }}</el-button>
            </el-popconfirm>
          </span>
          <span class="table-actionItem"
            ><el-button type="text" @click="handleExport(scope.row)"
              >导出</el-button
            ></span
          >
          <span class="table-actionItem">
            <el-popconfirm
              :title="`${
                scope.row.dataAuditEnable
                  ? '确定要关闭数据审计吗?'
                  : '确定要开启数据审计吗?'
              }`"
              placement="top"
              @confirm="handleAuditConfig(scope.row)"
            >
              <el-button type="text" slot="reference">{{
                scope.row.dataAuditEnable ? "关闭数据审计" : "开启数据审计"
              }}</el-button>
            </el-popconfirm>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="tr mt24">
      <x-pagination
        :total="total"
        :pageSize.sync="pageData.pageSize"
        :pageNo.sync="pageData.pageNo"
        @search="loadData()"
      />
    </div>
    <VerListModal ref="VerListModal" />
    <RuleErrorModal ref="RuleErrorModal"></RuleErrorModal>
  </div>
</template>

<script>
import MoveForm from "./__components__/moveForm";
import FolderForm from "./__components__/folderForm";
import RuleErrorModal from "./__components__/RuleErrorModal";
import { MODULE_TYPE_ENUM } from "@/utils/enum";

import {
  getHmmodelPageList,
  deleteHmmodel,
  putHmmodelPermissionctrl,
  getHmmodelExport,
  postHmmodelImport,
  putHmmodelDataauditctrl,
} from "@/apis/paas/HmModelController.js";
import {
  getHmmodelfolderPageList,
  deleteHmmodelfolder,
} from "@/apis/paas/HmModelFolderController.js";
import ModuleForm from "./__components__/moduleForm";
import VerListModal from "./__components__/VerListModal";
import { copy, exportAppDataFromJson } from "@/utils/util";
import DropdownButtons from "@/components/DropdownButtons/Index.vue";

const DEFAULT_FOLDER = 1;
export default {
  name: "ModelList",
  components: {
    VerListModal,
    RuleErrorModal,
    DropdownButtons,
  },

  data() {
    return {
      copy,
      loading: false,
      MODULE_TYPE_ENUM,
      queryData: {},
      pageData: {
        pageSize: 10,
        pageNo: 1,
      },
      tableData: [],
      total: 0,
      DEFAULT_FOLDER,
      currentFolder: {
        id: DEFAULT_FOLDER,
      },
      folderData: [],
      searchResFlag: false, // 是否查询结果
    };
  },
  computed: {
    isDefault() {
      return this.currentFolder.id === DEFAULT_FOLDER;
    },
  },
  created() {
    const {
      currentFolderId,
      currentFolderName,
      modelTypes,
      searchKey,
      searchResFlag,
      pageNo,
      pageSize,
    } = this.$route.query;
    this.currentFolder = {
      id: Number(currentFolderId),
      name: currentFolderName,
    };
    this.searchResFlag = searchResFlag === "true";
    this.$set(this.queryData, "searchKey", searchKey);
    if (modelTypes) {
      this.$set(this.queryData, "modelTypes", modelTypes.split(","));
    }
    if (pageSize) {
      this.pageData.pageSize = Number(pageSize);
    }
    if (pageNo) {
      this.pageData.pageNo = Number(pageNo);
    }

    this.loadData();
    this.loadFolderData();
  },

  methods: {
    async setAuth(row) {
      await putHmmodelPermissionctrl({
        modelCode: row.code,
        needPermissionCtrl: !row.permissionCtrl,
      });
      this.$message.success("操作成功");
      this.loadData();
    },
    // 加载当前文件夹下的数据
    // routerFlag 新建之后路由不replace,避免模型详情页面url异常
    loadData(pageNo = this.pageData.pageNo, searchFlag, routerFlag) {
      if (this.searchResFlag) searchFlag = "search";
      if (!this.currentFolder.id) {
        this.currentFolder = {
          id: this.DEFAULT_FOLDER,
        };
      }
      const params = {
        ...this.queryData,
        modelTypes: (this.queryData.modelTypes || []).join(","),
        ...this.pageData,
        folderId: this.currentFolder.id,
        pageNo,
      };
      if (searchFlag === "search") {
        delete params.folderId;
      }
      getHmmodelPageList(params).then((res) => {
        if (res.data.length === 0 && pageNo > 1) {
          this.loadData(pageNo - 1);
          return;
        }
        if (searchFlag === "search") {
          this.searchResFlag = true;
        } else {
          this.searchResFlag = false;
        }
        this.tableData = res.data;
        this.total = res.totalCount;
        this.pageData = {
          pageSize: res.pageSize,
          pageNo: res.pageNo,
        };
        if (routerFlag === "noRouterReplace") return;
        this.$router.replace({
          ...this.$route,
          query: {
            ...this.pageData,
            modelTypes: (this.queryData.modelTypes || []).join(","),
            searchKey: this.queryData.searchKey,
            searchResFlag: this.searchResFlag,
            currentFolderId: this.currentFolder.id,
            currentFolderName: this.currentFolder.name,
          },
        });
      });
    },

    handleReset() {
      this.queryData = {};
      this.loadData(1);
    },
    loadFolderData() {
      getHmmodelfolderPageList({
        pageSize: 10000,
        pageNo: 1,
      }).then((res) => {
        this._folderData = res.data;
        this.folderData = res.data.filter((item) => item.id !== DEFAULT_FOLDER);
      });
    },
    loadAllData() {
      this.searchResFlag = false;
      this.currentFolder = {
        id: this.DEFAULT_FOLDER,
        name: "",
      };
      this.pageData.pageNo = 1;
      this.loadData();
    },
    handleInfo(record) {
      this.$router.push({
        path: "/appModule/businessModule/info",
        query: {
          id: record.id,
        },
      });
    },

    handleCreate(command) {
      if (command === "model") {
        ModuleForm.addForm({
          folderId: this.currentFolder.id,
        }).then((data) => {
          this.$message.success("新增成功");
          const { id } = data;
          this.$router.push({
            path: "/appModule/businessModule/info",
            query: {
              id,
            },
          });
          this.loadData(1, "", "noRouterReplace");
        });
      } else if (command === "folder") {
        FolderForm.addForm().then(() => {
          this.$message.success("新增成功");
          this.loadFolderData();
        });
      }
    },

    handleEdit(record) {
      ModuleForm.editForm(record).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    handleVersionActivate(record) {
      this.$refs.VerListModal.open(
        {
          id: record.id,
        },
        () => {
          this.loadData();
        }
      );
    },

    handleDelete(record) {
      deleteHmmodel([record.id])
        .then((res) => {
          this.loadData();
          this.$message.success("操作成功");
        })
        .catch((e) => {
          if (e?.response?.status !== 700) return;
          const data = e?.response?.data || "";
          if (!data) return;
          this.$refs.RuleErrorModal.init(data);
        });
    },
    // 点击文件夹
    handleFolderClick(folder) {
      this.searchResFlag = false;
      this.currentFolder = folder;
      this.pageData.pageNo = 1;
      this.loadData();
    },
    handleFolderEdit(record) {
      FolderForm.editForm(record).then(() => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },

    handleFolderCommand(command, record) {
      if (command === "edit") {
        this.handleFolderEdit(record);
      } else if (command === "delete") {
        this.$confirm("确认要删除该文件夹吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.handleFolderDelete(record);
        });
      }
    },

    handleFolderDelete(record) {
      deleteHmmodelfolder([record.id]).then((res) => {
        this.loadFolderData();
        this.$message.success("操作成功");
      });
    },
    handleMove(record) {
      MoveForm.editForm(record, {
        folderList: this._folderData,
      }).then(() => {
        this.loadData();
        this.$message.success("操作成功");
      });
    },

    /**
     * 导出
     * @param {*} record
     */
    async handleExport(record) {
      const res = await getHmmodelExport({
        modelId: record.id,
      });
      await exportAppDataFromJson({
        data: res,
        key: record.code,
        ext: "hm_model",
      });

      setTimeout(() => {
        this.$message.success("导出成功");
      }, 1500);
    },

    /**
     * 导入
     * @param {*} file
     */
    async handleHttpRequest(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      await postHmmodelImport(formData, { folderId: this.currentFolder.id });
      this.$message.success("导入成功");
      this.loadData(1);
    },

    async handleAuditConfig(row = {}) {
      const { code: modelCode, dataAuditEnable } = row;
      await putHmmodelDataauditctrl({
        modelCode,
        enable: !dataAuditEnable,
      });
      this.$message.success("操作成功");
      this.loadData();
    },
  },
};
</script>

<style lang="scss" scoped>
.version-edit {
  color: #409eff;
  cursor: pointer;
}

.el-dropdown-menu {
  min-width: 100px;
}

.folder-card {
  border: 1px solid #dcdfe6;
  position: relative;
  cursor: pointer;

  ::v-deep .el-card__body {
    padding: 0;

    .folder-content {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      padding: 20px;
      box-sizing: border-box;
    }

    .menu {
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .el-icon-folder {
      font-size: 38px;
      color: #999;
      margin-right: 10px;
    }

    .el-icon-more {
      font-size: 18px;
      color: #999;
    }

    .folder-title {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
}

.root-link {
  color: #409eff;
  cursor: pointer;
  margin-right: 5px;
  font-weight: bold;
}
.limit {
  max-width: 200px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  display: inline-block;
}
</style>
